package com.xnyzc.lhy.order.service.impl.carpool;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.carpool.EUserStatus;
import com.xnyzc.lhy.common.penum.client.EClientUserType;
import com.xnyzc.lhy.common.penum.pay.EPayMoneyLock;
import com.xnyzc.lhy.common.penum.tab.ESidebar;
import com.xnyzc.lhy.common.penum.wallet.EIsDepartmentMoneyDisplayType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.order.entity.carpool.CheckPhoneRes;
import com.xnyzc.lhy.order.entity.sidebar.OaCUserOffice;
import com.xnyzc.lhy.order.entity.sidebar.OaSysSidebar;
import com.xnyzc.lhy.order.entity.system.OaSysGlobalConfig;
import com.xnyzc.lhy.order.entity.user.OaCUser;
import com.xnyzc.lhy.order.entity.user.OaCUserInfo;
import com.xnyzc.lhy.order.entity.user.tab.OaTabUser;
import com.xnyzc.lhy.order.entity.user.wallet.OaCWallet;
import com.xnyzc.lhy.order.mapper.sidebar.OaCUserOfficeMapper;
import com.xnyzc.lhy.order.mapper.sidebar.OaSysSidebarMapper;
import com.xnyzc.lhy.order.mapper.system.OaSysGlobalConfigMapper;
import com.xnyzc.lhy.order.mapper.user.OaCUserInfoMapper;
import com.xnyzc.lhy.order.mapper.user.OaCUserMapper;
import com.xnyzc.lhy.order.mapper.user.tab.OaTabUserMapper;
import com.xnyzc.lhy.order.mapper.user.wallet.OaCWalletMapper;
import com.xnyzc.lhy.order.service.carpool.InviteCarpoolCheckService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Description 邀约拼车校验
 * @Author zhuyubin
 * @Date 2019-09-25 13:05
 **/
@Slf4j
@Service
public class InviteCarpoolCheckServiceImpl implements InviteCarpoolCheckService {

    @Autowired
    private OaCUserMapper oaCUserMapper;
    @Autowired
    private OaSysGlobalConfigMapper oaSysGlobalConfigMapper;
    @Autowired
    private OaCUserInfoMapper oaCUserInfoMapper;
    @Autowired
    private OaCUserOfficeMapper oaCUserOfficeMapper;
    @Autowired
    private OaCWalletMapper oaCWalletMapper;
    @Autowired
    private OaTabUserMapper oaTabUserMapper;
    @Autowired
    private OaSysSidebarMapper oaSysSidebarMapper;

    /**
     * 检查乘客是否注册,如果未注册则自动注册
     * @param userId 乘客id
     * @param phone 手机号
     * @param name 乘客姓名
     * @param tag 用户来源
     * @return
     */
    @Override
    public CheckPhoneRes checkPhone(Long userId, String phone, String name, String tag){
        CheckPhoneRes checkPhoneRes = new CheckPhoneRes();
        // 全局配置获取游客部门id
        List<OaSysGlobalConfig> oaSysGlobalConfigs = oaSysGlobalConfigMapper.selectList(Wrappers.<OaSysGlobalConfig>lambdaQuery().eq(OaSysGlobalConfig::getTag, tag));
        // 用户基本
        List<OaCUser> oaCUserList = oaCUserMapper.selectList(Wrappers.<OaCUser>lambdaQuery().eq(OaCUser::getTag, tag).eq(OaCUser::getUserPhone, phone));
        if (oaSysGlobalConfigs.size() != 1){
            log.info(String.format("用户来源 %s 在全局配置中未获取到数据", tag));
            throw PangException.create(EErrorCode.registeredFailure);
        }
        OaSysGlobalConfig oaSysGlobalConfig = oaSysGlobalConfigs.get(0);
        Long individualOfficleId = oaSysGlobalConfig.getIndividualOfficleId();
        if (CheckUtil.objIsEmpty(individualOfficleId)){
            log.info(String.format("用户来源 %s 在全局配置中未配置散户部门", tag));
            throw PangException.create(EErrorCode.individualOfficleIdIsNull);
        }
        // 注册过
        if (oaCUserList.size() == 1){
            OaCUser oaCUser = oaCUserList.get(0);
            List<OaCUserOffice> oaCUserOfficeList = oaCUserOfficeMapper.selectList(Wrappers.<OaCUserOffice>lambdaQuery().eq(OaCUserOffice::getTag, tag).eq(OaCUserOffice::getUserId, oaCUser.getUserId()));
            if (oaCUserOfficeList.size() != 1){
                log.info(String.format("用户来源 %s 手机号 %s 未关联部门", tag, phone));
                throw PangException.create(EErrorCode.unOffice);
            }
            // 判断是否是游客部门
            Long officeId = oaCUserOfficeList.get(0).getOfficeId();
            if (individualOfficleId.equals(officeId)){
                checkPhoneRes.setUserStatus(EUserStatus.tourist.getValue());
                checkPhoneRes.setUserStatusMsg(EUserStatus.tourist.getDesc());
            } else {
                checkPhoneRes.setUserStatus(EUserStatus.office.getValue());
                checkPhoneRes.setUserStatusMsg(EUserStatus.office.getDesc());
            }
            checkPhoneRes.setOaCUser(oaCUser);
        }
        // 未注册
        else if (oaCUserList.size() == 0){
            checkPhoneRes.setUserStatus(EUserStatus.newUser.getValue());
            checkPhoneRes.setUserStatusMsg(EUserStatus.newUser.getDesc());
            // 生成用户
            OaCUser oaCUser = this.registeredUser(userId, phone, name, tag, individualOfficleId);
            checkPhoneRes.setOaCUser(oaCUser);
        } else {
            log.info(String.format("用户来源 %s 出现重复手机号 %s", tag, phone));
            throw PangException.create(EErrorCode.repeatPhone);
        }
        return checkPhoneRes;
    }

    /**
     * 用户注册
     * @param userId 乘客id
     * @param phone 手机号
     * @param name 乘客姓名
     * @param tag 用户来源
     * @param officeId 部门id
     */
    private OaCUser registeredUser(Long userId, String phone, String name, String tag, Long officeId){
        Date date = new Date();
        // 用户基础
        OaCUser oaCUser = new OaCUser();
        Long insertUserId = IDUtil.nextId();
        oaCUser.setUserId(insertUserId);
        oaCUser.setUserPhone(phone);
        oaCUser.setUserName(name);
        oaCUser.setTag(tag);
        oaCUser.setCreateUser(userId);
        oaCUser.setCreateTime(date);
        oaCUser.setUpdateUser(userId);
        oaCUser.setUpdateTime(date);
        int i = oaCUserMapper.insert(oaCUser);
        if (i != 1){
            log.info(String.format("用户来源 %s 插入用户基础表未成功", tag));
            throw PangException.create(EErrorCode.registeredFailure);
        }
        // 用户信息
        OaCUserInfo oaCUserInfo = new OaCUserInfo();
        oaCUserInfo.setInfoId(IDUtil.nextId());
        oaCUserInfo.setUserId(insertUserId);
        oaCUserInfo.setTag(tag);
        oaCUserInfo.setCreateUser(userId);
        oaCUserInfo.setCreateTime(date);
        oaCUserInfo.setUpdateUser(userId);
        oaCUserInfo.setUpdateTime(date);
        i = oaCUserInfoMapper.insert(oaCUserInfo);
        if (i != 1){
            log.info(String.format("用户来源 %s 插入用户信息表未成功", tag));
            throw PangException.create(EErrorCode.registeredFailure);
        }
        // 用户机构关联
        OaCUserOffice oaCUserOffice = new OaCUserOffice();
        oaCUserOffice.setLinkedId(IDUtil.nextId());
        oaCUserOffice.setUserId(insertUserId);
        oaCUserOffice.setOfficeId(officeId);
        oaCUserOffice.setTag(tag);
        oaCUserOffice.setCreateUser(userId);
        oaCUserOffice.setCreateTime(date);
        oaCUserOffice.setUpdateUser(userId);
        oaCUserOffice.setUpdateTime(date);
        i = oaCUserOfficeMapper.insert(oaCUserOffice);
        if (i != 1){
            log.info(String.format("用户来源 %s 插入用户机构关联表未成功", tag));
            throw PangException.create(EErrorCode.registeredFailure);
        }
        // 用户钱包
        BigDecimal zero = new BigDecimal("0");
        OaCWallet oaCWallet = new OaCWallet();
        oaCWallet.setWalletId(IDUtil.nextId());
        oaCWallet.setUserId(insertUserId);
        oaCWallet.setOfficeId(officeId);
        oaCWallet.setDeptOfficialBalance(zero);
        oaCWallet.setIsDeptAmount(EIsDepartmentMoneyDisplayType.yes.getType());
        oaCWallet.setIsDeptPay(EPayMoneyLock.yes.getType());
        oaCWallet.setPersonalOfficialBalance(zero);
        oaCWallet.setIsPersonalAmount(EIsDepartmentMoneyDisplayType.yes.getType());
        oaCWallet.setIsPersonalPay(EPayMoneyLock.yes.getType());
        oaCWallet.setWalletBalance(zero);
        oaCWallet.setIsBalancelPay(EPayMoneyLock.yes.getType());
        oaCWallet.setTag(tag);
        oaCWallet.setCreateUser(userId);
        oaCWallet.setCreateTime(date);
        oaCWallet.setUpdateUser(userId);
        oaCWallet.setUpdateTime(date);
        i = oaCWalletMapper.insert(oaCWallet);
        if (i != 1){
            log.info(String.format("用户来源 %s 插入用户钱包表未成功", tag));
            throw PangException.create(EErrorCode.registeredFailure);
        }
        // tab权限
        OaTabUser oaTabUser = new OaTabUser();
        oaTabUser.setLinkedId(IDUtil.nextId());
        oaTabUser.setCreateUser(userId);
        oaTabUser.setCreateTime(date);
        oaTabUser.setUpdateUser(userId);
        oaTabUser.setUpdateTime(date);
        oaTabUser.setUserId(userId);
        oaTabUser.setTabId(0);
        oaTabUser.setUserType(EClientUserType.c.getValue());
        oaTabUser.setTag(tag);
        i = oaTabUserMapper.insert(oaTabUser);
        if (i != 1){
            log.info(String.format("用户来源 %s 插入 tab 权限表未成功", tag));
            throw PangException.create(EErrorCode.registeredFailure);
        }
        // 侧边栏权限
        OaSysSidebar oaSysSidebar = new OaSysSidebar();
        oaSysSidebar.setSidebarId(IDUtil.nextId());
        oaSysSidebar.setCreateUser(userId);
        oaSysSidebar.setCreateTime(date);
        oaSysSidebar.setUpdateUser(userId);
        oaSysSidebar.setUpdateTime(date);
        oaSysSidebar.setUserId(userId);
        oaSysSidebar.setDictIds(String.format("%s,%s,%s", ESidebar.system.getIdStr(), ESidebar.car.getIdStr(), ESidebar.wallet.getIdStr()));
        oaSysSidebar.setDictAssociatedIds("23,");
        oaSysSidebar.setHaveSpecifiedVehicle(0);
        oaSysSidebar.setType("1");
        oaSysSidebar.setTag(tag);
        i = oaSysSidebarMapper.insert(oaSysSidebar);
        if (i != 1){
            log.info(String.format("用户来源 %s 插入侧边栏权限表未成功", tag));
            throw PangException.create(EErrorCode.registeredFailure);
        }
        return oaCUser;
    }
}
